import constants from '../constants'

function getMaxId() {
    let maxId = localStorage.getItem(constants.MaxId);
    let newId = maxId ? ++maxId : 1;
    localStorage.setItem(constants.MaxId, newId);
    return newId;
}

function getList() {
    const histories = localStorage.getItem(constants.History) ? JSON.parse(localStorage.getItem(constants.History)) : [];
    return histories.reverse(); //默认最近一次提交排在最前面
}

function saveHistory(record) {
    record.id = getMaxId();
    record.title = `QUESTION：第【${record.id}】次问卷提交记录`
    const histories = getList();
    histories.push(record);
    localStorage.setItem(constants.History, JSON.stringify(histories))
    return record.id;
}

function getHistory(id) {
    const histories = getList();
    const result = histories && histories.length && histories.filter(item => item.id === id);
    return result.length > 0 && result[0];
}

function deleteHistory(id) {
    const histories = getList();
    const result = histories && histories.length && histories.filter(item => item.id !== id); //过滤掉要删除的数据
    result.reverse(); //正序保存
    localStorage.setItem(constants.History, JSON.stringify(result));
    return result.reverse(); //倒序展示
}

export default {
    getList,
    saveHistory,
    getHistory,
    deleteHistory
}